package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties  weChatProperties;
    @Autowired
    private UserMapper  userMapper;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());
        //2. 判断当前OpenId是否为空 若为空 抛出业务异常 不为空 合法用户
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3. 判断当前用户对于外卖系统是否是新用户（该用户是否在用户表中）用OpenId查询用户表
        User user = userMapper.getByOpenid(openId);
        if(user == null){
            //4. 如果是新用户  自动完成注册
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //5. 返回用户对象
        return user;
    }

    /**
     * 调用微信接口服务 获取用户openId
     * @param code
     * @return
     */
    private String getOpenId(String code){
        //1. 调用微信服务器接口 或者当前微信用户的OpenId
        Map<String, String> map = new HashMap<>();
        //1.1 map中需要传递的参数：appid、secret、js_code、grant_type
        map.put("appid", weChatProperties.getAppid()); //微信分配给开发者的appid
        map.put("secret", weChatProperties.getSecret()); //微信分配给开发者的秘钥
        map.put("js_code", code); //用户登录成功后，微信返回的临时登录凭证code
        map.put("grant_type", "authorization_code");//授权类型 固定值
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");//拿到OpenId
        return openid;
    }
}
